#!/bin/bash

LOG_PATH="./logs/"

cat arp.txt | awk 'gsub(/\(/,b)gsub(/\)/,b)gsub(/:/,b){print $4,$2}' >arp_tmp.txt

# 获取mac地址对应的ip
function GetIpByMac() {
  cat arp_tmp.txt | grep $1 | awk '{print $2}'
}

# 截取文件名中的mac地址
function GetMacByFileName() {
  echo $1 | cut -c1-12
}

function FindErr() {
  FILE1=$LOG_PATH$FILE

  res=$(grep -w "$2" -rn $FILE1 | head -n 1)

  if [ -n "$res" ]; then
    echo $res
  fi
}

printf "%-16s %-16s %-36s %-10s\n" "ip" "mac" " uptime  of first error" "error type" >error.txt

# 循环遍历文件列表
for FILE in $(ls ./logs/); do
  res=$(FindErr $FILE 'GL error')

  if [ -n "$res" ]; then
    MAC=$(GetMacByFileName "$FILE")
    IP=$(GetIpByMac "$MAC")

        # 获取开机时间
        line=$(sed -n '2 p' ./logs/$FILE)

        t1=$(echo "$line" | cut -c1-14)
        t2=$(echo "$res" | cut -c8-21)

        printf "%-16s %-16s %-36s %-10s\n" "$MAC" "$IP" "'$t1 ~ $t2'" "GL error" >>error.txt
  fi

  res=$(FindErr $FILE 'GPU fault')
  if [ -n "$res" ]; then
    FILE=$(echo "$FILE" | cut -c1-12)
    FILE="$FILE"_logcat

    MAC=$(GetMacByFileName $FILE)
    IP=$(GetIpByMac "$MAC")

        # 获取开机时间
        line=$(sed -n '2 p' ./logs/$FILE)
        line2=$(tail -1 ./logs/$FILE)

        t1=$(echo $line | cut -c1-14)
        t2=$(echo $line2 | cut -c1-14)

        printf "%-16s %-16s %-36s %-10s\n" "$MAC" "$IP" "'$t1 ~ $t2'" "GPU fault" >>error.txt
  fi
done

rm arp_tmp.txt
